<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>通信设备易损性计算</h4>
			<el-form :inline="true" ref="queryRef" :rules="rules" label-position="right" :model="params"
				label-width="200px">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="编号：" class="form-item" prop="code">
							<el-input v-model="params.code" placeholder="" :disabled="true" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="楼房总高度：" class="form-item" prop="totalHeight">
							<el-input-number v-model="params.totalHeight" placeholder="请输入" :min="0"
								:disabled="disabled && !!route.query.operateType" clearable />
						</el-form-item>
					</el-col>
					<!-- <el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="userName">
							<el-input v-model="params.userName" placeholder="" clearable />
						</el-form-item>
					</el-col> -->
				</el-row>
				<!-- <el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人所属单位：" class="form-item" prop="orgName">
							<el-input v-model="params.orgName" placeholder="" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间：" class="form-item" prop="createTime">
							<el-date-picker v-model="params.createTime" type="date" value-format="YYYY-MM-DD"
								placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row> -->
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="场地分类：" class="form-item" prop="siteClassification">
							<el-select v-model="params.siteClassification" placeholder="请选择" class="form-select"
								:disabled="disabled && !!route.query.operateType" clearable>
								<el-option v-for="item in optionList1" :label="item.dictItemName"
									:value="item.dictItemCode">
								</el-option>
							</el-select>
						</el-form-item>

					</el-col>
					<el-col :span="11">
						<el-form-item label="年代：" class="form-item" prop="year">
							<el-input v-model="params.year" placeholder="请输入" :disabled="disabled" clearable />
							<!-- <el-select v-model="params.years" placeholder="请选择" class="form-select" :disabled="disabled"
								clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select> -->
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="设备类型：" class="form-item" prop="deviceType">
							<el-select v-model="params.deviceType" placeholder="请选择" class="form-select"
								:disabled="disabled && !!route.query.operateType" clearable>
								<el-option v-for="item in optionList4" :label="item.dictItemName"
									:value="item.dictItemCode">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
							<el-select v-model="params.fortification" placeholder="请选择" class="form-select"
								:disabled="disabled" clearable>
								<el-option v-for="item in optionList2" :label="item.dictItemName"
									:value="item.dictItemCode">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="设备所在区域：" class="form-item" prop="region">
							<el-select v-model="params.region" placeholder="请选择" class="form-select"
								:disabled="disabled && !!route.query.operateType" clearable>
								<el-option v-for="item in optionList6" :label="item.dictItemName"
									:value="item.dictItemCode">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11"></el-col>
				</el-row>
				<el-row v-if="isAdd" justify="end">
					<el-form-item class="bottom-button">
						<!-- <el-button type="primary" @click="showUploadDialog = true">参数导入</el-button> -->
						<el-button type="primary" @click="handleVerify" v-if="!route.query.id">验证</el-button>
						<el-button type="primary" @click="onCalc" v-if="route.query.id">计算</el-button>
						<el-button type="primary" @click="onSubmit" v-if="route.query.id">提交</el-button>
					</el-form-item>
				</el-row>
			</el-form>

			<el-form :inline="true" ref="tableRef" :rules="rules" label-position="right" :model="tableFormData">
				<h4 class="table-title">通讯设备水平地震作用力的计算 FH</h4>

				<!-- 数据导入弹框 -->
				<import-data v-if="showUploadDialog" v-model="showUploadDialog" ref="uploadDialog" :uploadUrl="uploadUrl"
					downloadFileName="通讯设备水平地震作用力的计算参数导入.xlsx" @importSuccess="onImport"></import-data>
				<el-table class="listTable" ref="multipleTableRef" border :data="tableFormData.tableData"
					:span-method="objectSpanMethod" style="width: 100%" :cell-style="{ border: '1px solid #e5ebf7', }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<!-- <el-table-column type="index" width="55" label="序号" /> -->
					<el-table-column prop="inFloor" header-align="center" align="center" label="楼层">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.inFloor`" :rules="rules.inFloor">
								<el-input type="number" v-model="scope.row.inFloor" :disabled="scope.row.disabled"
									size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="intensity" header-align="center" align="center" label="地震烈度" />
					<el-table-column header-align="center" align="center" label="楼层的地上高度（m）">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.aboveGroundHeight`"
								:rules="rules.aboveGroundHeight">
								<el-input type="number" v-model="scope.row.aboveGroundHeight"
									@change="onChangeHeight(scope.row, scope.$index, tableFormData.tableData)"
									:disabled="scope.row.disabled" size="small" :min="0"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" width="100">
						<template #header>
							<span class="color-red">W</span>设备自身及加固件总重量（N）
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.weight`" :rules="rules.weight">
								<el-input type="number" v-model="scope.row.weight"
									@change="onChangeTwEquipment(scope.row, scope.$index, tableFormData.tableData)"
									:disabled="scope.row.disabled" size="small" :min="0"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="k1" header-align="center" align="center">
						<template #header>
							<span class="color-red">K1</span>设备所在楼层反应系数
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" width="130">
						<template #header>
							<span class="color-red">T</span>设备自振周期（s）
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.naturalPeriod`" :rules="rules.naturalPeriod">
								<el-input-number v-model="scope.row.naturalPeriod" :disabled="scope.row.disabled" :min="0.01"
									:max="1" size="small" style="width: 100px;"></el-input-number>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="k2" header-align="center" align="center">
						<template #header>
							<span class="color-red">K2</span>设备对楼面反应系数
						</template>
					</el-table-column>
					<el-table-column prop="k3" header-align="center" align="center">
						<template #header>
							<span class="color-red">K3</span>设备重要度系数
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center">
						<template #header>
							<Formula tagOffset="-6px" :option="[
								{ content: 'α', sub: '0' },
							]"></Formula>
						</template>
						<template #default="scope">{{ scope.row.ao }}</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="αmax">
						<template #header>
							<Formula tagOffset="-6px" :option="[
								{ content: 'α', sub: 'max' },
							]"></Formula>
						</template>
						<template #default="scope">{{ scope.row.amax }}</template>
					</el-table-column>
					<el-table-column prop="result" header-align="center" align="center" width="140">
						<template #header>
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'α' },
								{ content: '=', margin: '0 8px' },
								{ content: 'α', sub: '0' },
								{ content: 'α', sub: 'max' },
							]"></Formula>
						</template>
					</el-table-column>
					<el-table-column prop="fh" header-align="center" align="center" width="160">
						<template #header>
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'F', sub: 'H' },
								{ content: '=', margin: '0 8px' },
								{ content: 'K', sub: '1' },
								{ content: 'K', sub: '2' },
								{ content: 'K', sub: '3' },
								{ content: 'a' },
								{ content: 'W' },
							]"></Formula>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="修正值">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.fhCorrect`" :rules="rules.fhCorrect">
								<el-input v-model="scope.row.fhCorrect" :disabled="scope.row.disabled"
									size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<!-- <el-table-column v-if="isAdd" label="操作" fixed="right" width="80">
						<template #default="{ $index, row }">
							<el-button @click.prevent="handleCalcdelete($index, row)" type="text"
								size="small">删除</el-button>
						</template>
					</el-table-column> -->
				</el-table>
				<!-- <el-button v-if="isAdd" class="add" style="width: 100%" plain @click="handleCalcAdd()">
					<el-icon style="vertical-align: middle">
						<Plus />
					</el-icon>
				</el-button> -->

				<h4 class="table-title">通讯设备竖向地震作用计算 FV</h4>
				<!-- <el-row v-if="isAdd" justify="end" class="table-tools-btn">
					<el-form-item class="bottom-button">
						<el-button type="primary" @click="showUploadDialog2 = true">参数导入</el-button>
						<el-button type="primary" @click="onCalc2">计算</el-button>
					</el-form-item>
				</el-row> -->
				<!-- 数据导入弹框 -->
				<import-data v-if="showUploadDialog2" v-model="showUploadDialog2" ref="uploadDialog2" :uploadUrl="uploadUrl"
					downloadFileName="通讯设备竖向地震作用计算参数导入.xlsx" @importSuccess="onImport2"></import-data>
				<el-table class="listTable" ref="multipleTableRef" border :data="tableFormData.tableData.slice(3, 5)"
					:span-method="objectSpanMethod2" style="width: 100%" :cell-style="{ border: '1px solid #e5ebf7', }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<!-- <el-table-column type="index" width="55" label="序号" /> -->
					<el-table-column prop="inFloor" header-align="center" align="center" label="楼层">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.inFloor`" :rules="rules.inFloor">
								<el-input type="number" v-model="scope.row.inFloor" :disabled="scope.row.disabled"
									size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="intensity" header-align="center" align="center" label="地震烈度" />
					<el-table-column header-align="center" align="center" label="楼层的地上高度（m）">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.aboveGroundHeight`"
								:rules="rules.aboveGroundHeight">
								<el-input type="number" v-model="scope.row.aboveGroundHeight"
									@change="onChangeHeight(scope.row, scope.$index, tableFormData.tableData, 2)"
									:disabled="scope.row.disabled" size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" width="100">
						<template #header>
							<span class="color-red">W</span>设备自身及加固件总重量（N）
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.weight`" :rules="rules.weight">
								<el-input type="number" v-model="scope.row.weight"
									@change="onChangeTwEquipment(scope.row, scope.$index, tableFormData.tableData, 2)"
									:disabled="scope.row.disabled" size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="k1" header-align="center" align="center">
						<template #header>
							<span class="color-red">K1</span>设备所在楼层反应系数
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" width="130">
						<template #header>
							<span class="color-red">T</span>设备自振周期（s）
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.naturalPeriod`" :rules="rules.naturalPeriod">
								<el-input-number v-model="scope.row.naturalPeriod" :disabled="scope.row.disabled" :min="0.01"
									:max="1" size="small" style="width: 100px;"></el-input-number>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="k2" header-align="center" align="center">
						<template #header>
							<span class="color-red">K2</span>设备对楼面反应系数
						</template>
					</el-table-column>
					<el-table-column prop="k3" header-align="center" align="center">
						<template #header>
							<span class="color-red">K3</span>设备重要度系数
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center">
						<template #header>
							<Formula tagOffset="-6px" :option="[
								{ content: 'α', sub: '0' },
							]"></Formula>
						</template>
						<template #default="scope">{{ scope.row.ao }}</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="αmax">
						<template #header>
							<Formula tagOffset="-6px" :option="[
								{ content: 'α', sub: 'max' },
							]"></Formula>
						</template>
						<template #default="scope">{{ scope.row.amax }}</template>
					</el-table-column>
					<el-table-column prop="result" header-align="center" align="center" width="140">
						<template #header>
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'α' },
								{ content: '=', margin: '0 8px' },
								{ content: 'α', sub: '0' },
								{ content: 'α', sub: 'max' },
							]"></Formula>
						</template>
					</el-table-column>
					<el-table-column prop="fv" header-align="center" align="center" width="190">
						<template #header>
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'F', sub: 'V' },
								{ content: '=', margin: '0 8px' },
								{ content: 'O.65K', sub: '1' },
								{ content: 'K', sub: '2' },
								{ content: 'K', sub: '3' },
								{ content: 'a' },
								{ content: 'W' },
							]"></Formula>
						</template>
					</el-table-column>
					<el-table-column prop="fvCorrect" header-align="center" align="center" label="修正值">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.fvCorrect`" :rules="rules.fvCorrect">
								<el-input v-model="scope.row.fvCorrect" :disabled="scope.row.disabled"
									size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<!-- <el-table-column v-if="isAdd" label="操作" fixed="right" width="80">
						<template #default="{ $index, row }">
							<el-button @click.prevent="handleCalcdelete2($index, row)" type="text"
								size="small">删除</el-button>
						</template>
					</el-table-column> -->
				</el-table>
				<!-- <el-button v-if="isAdd" class="add" style="width: 100%" plain @click="handleCalcAdd2()">
					<el-icon style="vertical-align: middle">
						<Plus />
					</el-icon>
				</el-button> -->
			</el-form>

			<!-- 版本查看 -->
			<GetVersion v-if="openDialog" v-model:open="openDialog" @recalculateVersion="recalculateVersion" type="9" />
			<el-dialog v-model="dialogVisible" @close="cancle" title="提示" width="500px">
				<p v-for="item in messageList">{{ item.label }}
					<el-popover placement="bottom" title="提示详情" :width="200" trigger="click">
						<template #reference>
							<span style="color: #107ce5;cursor: pointer;">提示详情</span>
						</template>
						<template #default>
							<p v-for="val in item.value">{{ val }}</p>
						</template>
					</el-popover>
				</p>
				<p>&nbsp;</p>
			</el-dialog>
		</div>
	</div>
</template>
 
<script setup>
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
// 接口
import { getInfo } from '@/api/login';
import {
	getByIdAndType,//查询
	caCeVulnerability,//计算
	saveCeVulnerability,//保存
	importCeVulnerabilityUrl, // 参数导入
	recalculateCe,//验证
	saveCeResult,//计算保存
} from "@/api/lifelineVulnerAnalysis/lifelineVulnerAnalysis.js";
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
// 公用方法
import { parseTime } from "@/utils/ruoyi.js";
// 引入公式组件
import Formula from '@/components/Formula';
import GetVersion from '../underPipeNet/dataFile/Version.vue';
// import MultilineFormula from '@/components/Formula/multiline';
// 引入导入弹框
import ImportData from "@/components/ImportData";

// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 当前实例
const { proxy } = getCurrentInstance();
// 当前路由
const route = useRoute();
const router = useRouter();

// 打开类型，query为查看
let operateType = computed(() => route.query.operateType || false);
// 是否是新增页，有路由参数是详情页，否则是新增页
let isAdd = computed(() => (route.query.id && route.query.operateType ? false : true));
// 禁用
const disabled = ref(false);
// 地震烈度
const arrIntensity = [6, 7, 8, 9, 10];

//最多保留N小数 ,N 在 options {decimals: N} 中定义
const positivedecimals = (rule, value, callback) => {
	value = String(value);
	if (
		value.indexOf(".") != -1 &&
		(value.split(".").length > rule.options.decimals ||
			value.split(".")[0] === "" ||
			value.split(".")[1] === "")
	) {
		callback(new Error()); //防止输入多个小数点
	} else if (
		value.indexOf(".") != -1 &&
		value.split(".")[1].length > rule.options.decimals
	) {
		callback(new Error()); //小数点后两位
	} else {
		callback();
	}
};
//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
	if (value == '' || value == undefined || value == null) {
		callback();
	} else if (isNaN(Number(value))) {
		callback(new Error('请输入yyyy格式如2022'));
	} else if (value.toString().length != 4) {
		callback(new Error('请输入yyyy格式如2022'));
	} else if (value.toString().indexOf(".") != -1) {
		callback(new Error('请输入yyyy格式如2022'));
	} else {
		callback();
	}
}

const data = reactive({
	// 表单参数
	params: {
		code: "",//编号
		siteClassification: "",//场地分类
		year: "",//年代
		fortification: "", //设防情况
		deviceType: "", //设备类型
		region: "", //设备所在区域
		totalHeight: undefined, //楼房总高度
		createTime: parseTime(new Date()), //维护时间
		userName: userName.value, //维护人
		orgName: orgName.value, //维护人所属单位
	},
	// 场地分类，候选值：I、II、Ⅲ、IV
	siteClassificationOptions: dictStore.siteClassificationOptions || [],
	// 设防情况，候选值为：请选择、未设防、6度、7度、8度、9度、自设防、其他
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions1 || [],
	// 设备类型，候选值：蓄电池、配电设备、通信设备
	equipmentCategoryOptions: [
		{
			value: '蓄电池',
			label: '蓄电池'
		}, {
			value: '配电设备',
			label: '配电设备'
		}, {
			value: '通信设备',
			label: '通信设备'
		}
	],
	// 设备所在区域，候选值：省中心及以上、地区（市）局、县局
	regionOptions: [
		{
			value: '省中心及以上',
			label: '省中心及以上'
		}, {
			value: '地区（市）局',
			label: '地区（市）局'
		}, {
			value: '县局',
			label: '县局'
		}
	],
	// 表单验证规则
	rules: {
		siteClassification: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		year: [
            {
                required: true,
                message: "请输入正确数值",
                validator: isYearNotMust,
                trigger: ["change", "blur"],
            }
        ],
		deviceType: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		fortification: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		region: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		totalHeight: [
			{ required: true, message: '请输入', trigger: 'change' }
		],
		// 楼号
		inFloor: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		// 设备自身及加固件总重量（N）
		weight: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		// 周期
		t: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		// 修正值
		fhCorrect: [
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		// k2: [
		//     { required: true, message: "请输入", trigger: "blur" },
		//     {
		//         message: "请输入正确数值，最多保留四位小数",
		//         validator: positivedecimals,
		//         options: { decimals: 4 },
		//         trigger: ["change", "blur"],
		//     },
		// ],
		// k3: [
		//     { required: true, message: "请输入", trigger: "blur" },
		//     {
		//         message: "请输入正确数值，最多保留四位小数",
		//         validator: positivedecimals,
		//         options: { decimals: 4 },
		//         trigger: ["change", "blur"],
		//     },
		// ],
		// aboveGroundHeight: [
		//     { required: true, message: "请输入", trigger: "blur" },
		//     {
		//         message: "请输入正确数值，最多保留四位小数",
		//         validator: positivedecimals,
		//         options: { decimals: 4 },
		//         trigger: ["change", "blur"],
		//     },
		// ],
		// a0: [
		//     { required: true, message: "请输入", trigger: "blur" },
		//     {
		//         message: "请输入正确数值，最多保留四位小数",
		//         validator: positivedecimals,
		//         options: { decimals: 4 },
		//         trigger: ["change", "blur"],
		//     },
		// ],
	},
	// 表格
	tableFormData: {
		tableData: [
		],
		tableData: [
		]
	}
});
const {
	params,
	fortificationOptions,
	yearsOptions,
	siteClassificationOptions,
	regionOptions,
	equipmentCategoryOptions,
	rules,
	tableFormData,
} = toRefs(data);

// 获取用户
function getUserInfo(userId) {
	getInfo(userId).then(response => {
		const { user } = response;
		if (user) {
			params.value.userName = user.userName;
			params.value.maintainerUnit = user.orgName;
		}
	});
};

// 表格
const multipleTableRef = ref();
// 表格新增行
const handleCalcAdd = () => {
	const arr = [...tableFormData.value.tableData];
	tableFormData.value.tableData = arr.concat(setAddRowFiled(arr));
}
const handleCalcAdd2 = () => {
	const arr = [...tableFormData.value.tableData];
	tableFormData.value.tableData = arr.concat(setAddRowFiled(arr, 1));
}
// 设置新增行字段
function setAddRowFiled(list, range) {
	const arr = [];
	// 获取楼层号
	let storey = 0;
	if (list && list.length) {
		storey = list[list.length - 1].storey || 0;
	}
	// 设置烈度
	if (arrIntensity && arrIntensity.length) {
		arrIntensity.filter(item => !!range ? item >= 9 : true)
			.map(item => {
				arr.push({
					storey: storey + 1,
					intensity: item,
					k1: '',
					t: undefined,
					k2: '',
					k3: "",
					aboveGroundHeight: "",
					a0: "",
					amax: "",
					a: '',
					fh: '',
					fhCorrect: ''
				})
			})
	}
	return arr;
}
// 表格合并行
const objectSpanMethod = ({
	row,
	column,
	rowIndex,
	columnIndex,
}) => {
	if (columnIndex === 0 || columnIndex === 2 || columnIndex === 3 || columnIndex === 5 || columnIndex === 13) {
		if (rowIndex % 5 === 0) {
			return {
				rowspan: 5,
				colspan: 1,
			}
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			}
		}
	}
}
// 表格合并行
const objectSpanMethod2 = ({
	row,
	column,
	rowIndex,
	columnIndex,
}) => {
	if (columnIndex === 0 || columnIndex === 2 || columnIndex === 3 || columnIndex === 5 || columnIndex === 13) {
		if (rowIndex % 2 === 0) {
			return {
				rowspan: 2,
				colspan: 1,
			}
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			}
		}
	}
}
// 表格1，删除行
const handleCalcdelete = (index, row) => {
	deleteRow(tableFormData.value.tableData, index, row);
}
// 表格2，删除行
const handleCalcdelete2 = (index, row) => {
	deleteRow(tableFormData.value.tableData, index, row);
}
// 删除行
function deleteRow(arr = [], index, row) {
	if (arr && arr.length) {
		for (let i = arr.length - 1; i >= 0; i--) {
			if (arr[i].storey == row.storey) {
				arr.splice(i, 1);
			}
		}
	}
}


// 设置楼层的地上高度
function onChangeHeight(row, index, arr, rowLen = 5) {
	if (arr && arr.length) {
		for (let i = 0; i < rowLen; i++) {
			const item = arr[index + i];
			item.aboveGroundHeight = Number(row.aboveGroundHeight);
		}
	}
}
// 设置设备自身及加固件总重量（N）
function onChangeTwEquipment(row, index, arr, rowLen = 5) {
	if (arr && arr.length) {
		for (let i = 0; i < rowLen; i++) {
			const item = arr[index + i];
			item.weight = Number(row.weight);
		}
	}
}

// 导入弹框是否显示
let showUploadDialog = ref(false);
let showUploadDialog2 = ref(false);
// 导入数据接口路径
const uploadUrl = ref(importCeVulnerabilityUrl);
// 导入成功回调
const onImport = (response, uploadFile, uploadFiles) => {
	const { code, data } = response;
	if (code == 200 && data) {
		proxy.$modal.msgSuccess('导入数据成功!');
		// 列表数据回显
		tableFormData.value.tableData = [...data];
	}
}
// 导入成功回调
const onImport2 = (response, uploadFile, uploadFiles) => {
	const { code, data } = response;
	if (code == 200 && data) {
		proxy.$modal.msgSuccess('导入数据成功!');
		// 列表数据回显
		tableFormData.value.tableData = [...data];
	}
}
// 通信设备计算
const onCalc = () => {
	proxy.$refs['queryRef'].validate((valid, fields) => {
		if (valid) {
			const formData = tableFormData.value.tableData[0];
			let query = {
				...params.value,
				"region": params.value.region || "地区（市）局", //区域
				id: formData.id,
				site:params.value.siteClassification,
				inFloor: formData.inFloor,
				aboveGroundHeight:formData.aboveGroundHeight,
				weight: formData.weight,
				naturalPeriod: formData.weight,
				k3Ids: formData.k3Ids,
				maxIds: formData.maxIds,
			}
			proxy.$modal.loading('正在努力计算,请耐心等待！');
			caCeVulnerability(query).then((res) => {
				proxy.$modal.closeLoading();
				const { code, data } = res;
				if (code === 200 && data) {
					tableFormData.value.tableData = [...data];
					proxy.$modal.msgSuccess('计算完成！计算结果未保存，若需保存结果，请计算后点击提交按钮！');
				} else {
					proxy.$modal.msgError('计算失败！');
				}
			}).catch(err => {
				proxy.$modal.closeLoading();
				console.log(err.message);
			});
		} else {
			proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0])
		}
	})
};

// 通信设备保存FV
const onSubmit = () => {
	proxy.$refs['queryRef'].validate((valid, fields) => {
		if (valid) {
			let query = {
				type: '9',
				devicesParam: {
					...params.value,
					id: formData.id,
					site:params.value.siteClassification,
					inFloor: formData.inFloor,
					aboveGroundHeight: formData.aboveGroundHeight,
					weight: formData.weight,
					naturalPeriod: formData.weight,
					k3Ids: formData.k3Ids,
					maxIds: formData.maxIds,
				}
			}
			proxy.$modal.loading('正在保存,请耐心等待！');
			saveCeVulnerability(query).then((res) => {
				proxy.$modal.closeLoading();
				const { code, data } = res;
				if (code === 200) {
					tableFormData.value.tableData = [...data];
					proxy.$modal.msgSuccess("保存成功！");
					// 延迟跳转
					setTimeout(() => {
						router.push('/lifelineVulnerAnalysis/lifelineMain')
					}, 1500)
				}
			}).catch(err => {
				proxy.$modal.closeLoading();
				console.log(err.message);
			});
		} else {
			proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0])
		}
	})
}

// 显示弹框
const openDialog = ref(false)
const handleVerify = () => {
	openDialog.value = true;
}
// 验证
const messageList = ref([]);
const dialogVisible = ref(false);
const cancle = () => {
	dialogVisible.value = false;
}
const recalculateVersion = (version) => {
	openDialog.value = false;
	recalculateCe({ versionId:version.id, type: '9' }).then(res => {
		if (JSON.stringify(res.data) == '{}') {
			ElMessageBox.confirm(
				'数据通过验证，是否计算？', '提示',
				{
					confirmButtonText: '计算并保存',
					cancelButtonText: '取消',
					type: 'success',
				}
			)
				.then(() => {
					saveCeResult({ versionId:version.id }).then(response => {
						if (response.code == 200) {
							router.push(`/lifelineVulnerAnalysis/lifelineMain?type=9`)
						}
					})
				}).catch(() => { })
		} else {
			const { data } = res;
			messageList.value = [];
			for (let i in data) {
				messageList.value.push({ label: `第${i}行计算参数未填写完整，请补充完整再计算。`, value: data[i] })
			}
			dialogVisible.value = true;
		}
	})
}

// 获取数据
function getData(query) {
	getByIdAndType(query).then((res) => {
		const { code, data } = res;
		if (code === 200 && data) {
			const { tableEntity, devicesValueVoList, devicesVo } = data;
			// 基础信息
			if (tableEntity) {
				params.value = { ...tableEntity };
				params.value.siteClassification = devicesVo.site;
				params.value.region = devicesVo.region;
				params.value.deviceType = devicesVo.deviceType;
				params.value.totalHeight = devicesVo.totalHeight;
				// 维护时间
				const dateTime = new Date()
				params.value.createTime = parseTime(dateTime);
				// 根据id获取用户信息
				params.value.userName = userStore.name;
				params.value.orgName = userStore.orgName;
			}
			// FH表格数据回显
			tableFormData.value.tableData = [];
			if (devicesValueVoList) {
				devicesValueVoList.forEach((item) => {
					item.isEdit = false;
					item.disabled = operateType.value === 'query' ? true : false;
					tableFormData.value.tableData.push({
						...item,
						aboveGroundHeight: devicesVo.aboveGroundHeight,
						weight: devicesVo.weight,
						naturalPeriod: devicesVo.naturalPeriod,
						inFloor: devicesVo.inFloor,
					});
				});
			}
		}
	}).catch(err => {
		console.log(err);
	});
}
//字典表查询
const optionList1 = ref([])
const optionList2 = ref([])
const optionList3 = ref([])
const optionList4 = ref([])
const optionList5 = ref([])
const optionList6 = ref([])
const optionList7 = ref([])
const optionList8 = ref([])
/** 获取字典值 */
async function getDictData() {
	await getValidDictItemsByDictCode("smxcdlb").then(response => {
		optionList1.value = response.data;//场地类别
	});
	await getValidDictItemsByDictCode("smxsfqk").then(response => {
		optionList2.value = response.data;//设防情况
	});
	await getValidDictItemsByDictCode("smxjsnd").then(response => {
		optionList3.value = response.data;//建造年代
	});
	await getValidDictItemsByDictCode("smxtxsblb").then(response => {
		optionList4.value = response.data;//设备类别
	});
	await getValidDictItemsByDictCode("smxtxsblb").then(response => {
		optionList5.value = response.data;//设备固定形式
	});
	await getValidDictItemsByDictCode("smxtxsbszqy").then(response => {
		optionList6.value = response.data;//设备所在区域
	});
	await getValidDictItemsByDictCode("smxtxsbazqk").then(response => {
		optionList7.value = response.data;//安装情况
	});
	await getValidDictItemsByDictCode("smxtxsbszlc").then(response => {
		optionList8.value = response.data;//所在楼层
	});
}
getDictData()
// 挂载
onMounted(() => {
	const id = route.query.id;
	if (id) {
		disabled.value = true;
		// 获取数据
		getData({ id, type: 9 });
	} else {
		disabled.value = false;
	}
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}

	// 字体红色
	.color-red {
		color: red !important;
	}

	// 表格标题
	.table-title {
		margin-top: 50px;
	}

	// 表格工具按钮组
	.table-tools-btn {
		margin-top: -50px;
		float: right;
	}
}</style>


